
/**
 * Copyright 2014-2020  the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.upb.webserver.developerappmap;

import com.upb.webserver.account.AccountService;
import com.upb.webserver.common.exception.WebServerException;
import com.upb.webserver.common.pojo.account.AccountCommon;
import com.upb.webserver.common.pojo.application.RspAppKeyVO;
import com.upb.webserver.common.pojo.base.BaseResponse;
import com.upb.webserver.common.returncode.ConstantCode;
import com.upb.webserver.common.tools.JsonUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.spec.InvalidKeySpecException;
import java.util.List;

@Log4j2
@RestController
@RequestMapping(value = "developer-app")
public class DeveloperAppMapController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private DeveloperAppMapService developerAppMapService;

    /**
     * @param request
     * @return
     */
    @GetMapping(value = "app-key-list")
    public BaseResponse queryApplicationKeyLis(HttpServletRequest request) {
        log.info("start exec method [queryApplicationKeyLis].");
        AccountCommon accountCommon = accountService.getAccountCommon(request);
        List<RspAppKeyVO> list = developerAppMapService.queryAppKeyList(accountCommon.getPlatform(), accountCommon.getId());

        BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS, list);
        log.info("success exec method [queryApplicationKeyLis].");
        log.debug("success exec method [queryApplicationKeyLis]. result:{}", JsonUtils.objToString(baseResponse));
        return baseResponse;
    }


    /**
     * @param id
     * @param passwordBase64
     * @param response
     * @return
     * @throws InvalidKeySpecException
     */
    @GetMapping("privateKey/download")
    public void downLoadPrivateKeyP12(@RequestParam(value = "id") Integer id,
                                      @RequestParam(value = "passwordBase64") char[] passwordBase64,
                                      HttpServletResponse response, HttpServletRequest request) throws InvalidKeySpecException, UnsupportedEncodingException {
        log.info("start exec method [downLoadPrivateKeyP12]. id:{}", id);

        if (null == passwordBase64 || passwordBase64.length == 0)
            throw new WebServerException(ConstantCode.PASSWORD_BASE64_EMPTY);

        AccountCommon accountCommon = accountService.getAccountCommon(request);
        String fileFullName = developerAppMapService.getPKCS12OfPrivateKey(accountCommon.getPlatform(), accountCommon.getId(), id, passwordBase64);

        //response
        File file = new File(fileFullName);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        String fileName = fileFullName.substring(fileFullName.lastIndexOf(File.separator) + 1);
        response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
        response.setHeader("fileName", java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis);
             OutputStream os = response.getOutputStream()) {
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            log.warn("fail exec method [downLoadPrivateKeyP12]. id:{}", id, e);
        }
    }
}
